#!/usr/bin/python2.5
# -*- coding: utf-8 -*-
#
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import re
import tipfy

from tipfy.ext.i18n import gettext as _
from tipfy.ext import wtforms
from tipfy.ext.wtforms import fields
from tipfy.ext.wtforms import validators

from apps.pf_mobile import handlers
from apps.pf_mobile import pfapi
from apps.pf_mobile.utils import jp_mobile_carriers

class NumberOrEmail(validators.Email):
  def __init__(self, message=None):
    super(NumberOrEmail, self).__init__(message)

  def __call__(self, form, field):
    if self.message is None:
      self.message = field.gettext(_(u'Invalid contact info.'))
    field.flags.is_email = False
    field.flags.is_number = False
    try:
      super(NumberOrEmail, self).__call__(form, field)
      field.flags.is_email = True
    except validators.ValidationError:
      maybe_number = jp_mobile_carriers.get_phone_number(field.data)
      if (not maybe_number or
          not jp_mobile_carriers.is_mobile_number(maybe_number)):
        raise validators.ValidationError(self.message)
      field.flags.is_number = True

class PersonForm(wtforms.Form):
  author_name = fields.TextField(_(u'あなたの名前'),
                                 validators=[validators.Required()])
  author_phone = fields.TextField(u'Author Phone')
  source_name = fields.TextField(u'Source Name')
  source_date = fields.DateField(u'Source Date')
  source_url = fields.TextField(u'Source Url')
  first_name = fields.TextField(_(u'名'), validators=[validators.Required()])
  last_name = fields.TextField(_(u'姓'), validators=[validators.Required()])
  home_city = fields.TextField(_(u'住所(町名まで)'))
  home_state = fields.TextField(u'Home State')
  home_neighborhood = fields.TextField(u'Neighborhood')
  home_street = fields.TextField('Home Street')
  home_zip = fields.TextField('Home zip')
  photo_url = fields.TextField('Photo url')
  other = fields.TextAreaField('Other')

class NoteForm(wtforms.Form):
  found = fields.HiddenField(u'found')
  status = fields.HiddenField(u'status')
  last_known_location = fields.TextField(_(u'現在の所在'))
  text = fields.TextAreaField(_(u'状況'))

class CreateForm(wtforms.Form):
  person = fields.FormField(PersonForm)
  note = fields.FormField(NoteForm)
  found_person_contact = fields.TextField(
      _(u'メール又は電話(情報は保護され閲覧にはPCが必要)'),
      validators=[validators.Optional(), NumberOrEmail()])
  author_email = fields.TextField(_(u'メールアドレス'),
                                  validators=[validators.Optional(),
                                              validators.Email()])

class CreateHandler(handlers.BaseHandler):
  def get(self, **kwargs):
    return self.render_response('create.html', form=self.form,
                                error=kwargs.get('error', ''))

  def post(self, **kwargs):
    if not self.form.validate():
      return self.get(error=_(u'入力に誤りがあります(赤くなった項目を確認してください)'))

    person = pfapi.Person(**self.form.person.data)
    note = pfapi.Note(**self.form.note.data)
    note.status = 'believed_alive'
    note.found = True
    note.author_name = person.author_name
    if self.form.found_person_contact.flags.is_email:
      note.email_of_found_person = self.form.found_person_contact.data
    elif self.form.found_person_contact.flags.is_number:
      note.phone_of_found_person = self.form.found_person_contact.data
    if hasattr(person, 'author_email'):
      note.author_email = person.author_email
    if hasattr(person, 'author_phone'):
      note.author_phone = person.author_phone
    person.notes.append(note)
    api = pfapi.PfApi()
    try:
      result = api.create([person.to_dict()])
    except pfapi.PfApiError:
      return self.get(error=_(u'エラーが発生しました'))
    author_email = self.form.author_email.data
    email_added = '0'
    if author_email:
      api.subscribe(person.person_record_id, author_email)
      email_added = '1'
    return self.redirect_to('view', {'id': person.person_record_id,
                                     'added': '1',
                                     'email_added': email_added})

  @tipfy.cached_property
  def form(self):
    return CreateForm(self.request)
